<template>
  <div>
    <NavBar></NavBar>
    <!-- 代理人 -->
    <Loading :loading="loading">
      <van-form class="c-d921q5">
        <div class="c-d921q5-item">
          <div class="c-d921q5-item-title">代理人</div>
          <div class="c-d921q5-item-value flex-row flex-align-center">
            <div class="c-d921q5-item-label">兼职代理人</div>
            <van-field
              v-model="info.agent"
              name="agent"
              placeholder="请选择兼职代理人"
              :rules="formRules.agent"
            />
            <img
              class="c-d921q5-item-img"
              src="./img/doc.png"
              @click="
                $refs.peoName.visible = true
                $refs.peoName.value = info.agent
              "
            />
            <PeoList
              ref="peoName"
              @confirm="value => getPartimer(value)"
              :columns="peopleList"
            />
          </div>
        </div>
        <div class="c-d921q5-item">
          <div class="c-d921q5-item-title">上传保单图片</div>
          <div>
            <van-uploader
              class="c-d921q5-item-upload"
              v-model="fileList"
              multiple
              :after-read="afterRead"
              :before-delete="beforeDelete"
            >
              <img src="./img/upload.png" />
            </van-uploader>
          </div>
        </div>
        <div>
          <van-button
            type="primary"
            @click="hundleSubmit"
            display="block"
            class="submit"
          >
            提交
          </van-button>
        </div>
      </van-form>
    </Loading>
  </div>
</template>
<script>
import PeoList from '@/components/peoList'
import NavBar from '@/components/h5header'
import API from '@/services/h5/product'
import comAPI from '@/services/h5/common'
import Loading from '@/components/data-loading'
import { mapState, mapMutations, mapActions } from 'vuex'
export default {
  components: {
    NavBar,
    PeoList,
    Loading
  },
  data() {
    return {
      info: {
        agent: ''
      },
      peopleList: [],
      fileList: [],
      formRules: {
        agent: [{ required: true, message: '请输入代理人姓名' }]
      }
    }
  },
  watch: {
    peopleList(val) {
      if (val.length == 1) {
        this.info.agent = val[0].name
      }
    }
  },
  computed: {
    ...mapState('loading', ['loading']),
    ...mapState('carProduct', ['policyFiles'])
  },

  mounted() {
    this.getPartTimerList()
  },
  methods: {
    ...mapMutations('loading', ['setLoading']),
    ...mapMutations('carProduct', ['setPolicyFiles']),

    ...mapActions('carProduct', ['getProductDetailInfo']),
    async getPartTimerList() {
      this.setLoading(true)

      await this.getProductDetailInfo({
        contractId: this.$route.query.contractId
      })
      this.fileList = this.policyFiles
      let customer = await API.getPartTimerList()
      if (customer.data && customer.data.code === 1000) {
        this.peopleList = []
        customer.data.data.forEach(item => {
          this.peopleList.push({
            label: item.name,
            value: item.partTimerId,
            ...item
          })
        })
      }
      this.setLoading(false)
    },
    getPartimer(value) {
      this.info.agent = value.name
      this.info.partTimerId = value.partTimerId
    },
    async beforeDelete(file, detail) {
      console.log('dfsdfsdsdfsd', detail)
      return new Promise((resolve, reject) => {
        this.$dialog
          .confirm({
            title: '确认删除此张照片吗？'
          })
          .then(() => {
            if (file.id) {
              comAPI.delFile([{ id: file.id }]).then(res => {
                res.data &&
                  res.data.code === 1000 &&
                  this.$message.success('删除成功')
              })
            }
            API.getProductDetailInfo({
              contractId: this.$route.query.contractId
            }).then(detailRes => {
              const getPolicyFiles = arr => {
                if (arr.length == 0) return []
                let data = []
                arr.forEach(item => {
                  data.push({
                    url: item.filePath,
                    id: item.id
                  })
                })
                return data
              }
              this.setLoading(false)
              detailRes.data &&
                detailRes.data.code === 1000 &&
                this.setPolicyFiles(
                  getPolicyFiles(detailRes.data.data.policyFiles)
                )
            })
            resolve()
          })
          .catch(err => {
            this.$message.warning('已取消')
            reject(err)
          })
      })
    },
    afterRead(file) {
      let fileData = new FormData()
      let param = {
        businessId: this.$route.query.contractId,
        attachmentType: 109,
        attachmentSubType: ''
      }
      fileData.append('param', JSON.stringify(param))
      if (!file.length) {
        fileData.append('files', file.file)
      } else {
        for (let i = 0; i < file.length; i++) {
          fileData.append('files', file[i].file)
        }
      }
      this.setLoading(true)
      comAPI.upload(fileData).then(res => {
        if (res.data && res.data.code === 1000) {
          this.setLoading(false)
          this.$message.success('上传成功')

          API.getProductDetailInfo({
            contractId: this.$route.query.contractId
          }).then(detailRes => {
            const getPolicyFiles = arr => {
              if (arr.length == 0) return []
              let data = []
              arr.forEach(item => {
                data.push({
                  url: item.filePath,
                  id: item.id
                })
              })
              return data
            }
            this.setLoading(false)
            detailRes.data &&
              detailRes.data.code === 1000 &&
              this.setPolicyFiles(
                getPolicyFiles(detailRes.data.data.policyFiles)
              )
          })
        }
      })
    },
    hundleSubmit() {
      let params = {
        contractId: this.$route.query.contractId,
        partTimerId: this.info.partTimerId
      }
      if (this.info.agent != '' && this.fileList.length !== 0) {
        this.setLoading(true)
        API.saveReceiver(params).then(res => {
          if (res.data && res.data.code === 1000) {
            this.setLoading(false)
            this.$router.push(`/submitSuccess/${this.$route.query.contractId}`)
          }
        })
      } else {
        this.$message.error('请完整填写信息')
      }
    }
  }
}
</script>
<style lang="less" scoped>
.submit {
  width: 345px;
  margin: 15px;
  border-radius: 4px;
  color: white;
}
.c-d921q5 {
  // height: calc(100% - 55px - 85px);
  // overflow-y: scroll;
  box-sizing: border-box;
  border: 0.1px solid transparent;
}
.c-d921q5-item {
  margin-top: 13px;
  background: #ffff;
  padding: 15px;
  box-shadow: rgba(0, 0, 0, 0.05) 0 1px 2px 0;
  &-title {
    font-size: 19px;
    color: #000;
    font-weight: bold;
    &-txt {
      font-size: 13px;
      color: #999;
      font-weight: normal;
    }
  }
  &-img {
    width: 15px;
    height: 15px;
  }
  &-left {
    width: 7px;
    height: 13px;
  }
  &-value {
    /deep/.van-field--error .van-field__control::placeholder {
      color: #999;
    }
    // margin-top: 15px;
    border-bottom: 0.5px solid #e9e9e9;
    &:last-child {
      border: none;
    }
  }
  &-label {
    font-size: 15px;
    color: #333;
    width: 120px;
  }
  &-upload {
    margin-top: 13px;
    img {
      width: 70px;
      height: 70px;
    }
    /deep/ .van-uploader__preview-image {
      width: 70px;
      height: 70px;
    }
  }
}
</style>
